package org.bluedream.core.utils;


import org.bluedream.comm.utils.EmptyUtil;
import org.yaml.snakeyaml.Yaml;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class YmlRead {
    private static final String[] DEFAULT_CONFIG_FILE = new String[]{"application-dev.yml" , "application.yml"};
    // ${} 占位符 正则表达式
    private static Pattern p1 = Pattern.compile("\\$\\{.*?\\}");

    private YmlRead(){
        throw new AssertionError();
    }

    /**
     * key:文件索引名
     * value：配置文件内容
     */
    private static Map<String , LinkedHashMap> ymls = new HashMap<>();
    /**
     * String:当前线程需要查询的文件名
     */
    private static ThreadLocal<String> nowFileName = new InheritableThreadLocal<>();

    /**
     * 加载配置文件
     * @param fileName
     */
    public static void loadYml(String fileName){
        nowFileName.set(fileName);
        if (!ymls.containsKey(fileName)){
            ymls.put(fileName , new Yaml().loadAs(YmlRead.class.getResourceAsStream("/" + fileName),LinkedHashMap.class));
        }
    }

    /**
     * 读取yml文件中的某个value。
     * 支持解析 yml文件中的 ${} 占位符
     * @param key
     * @return Object
     */
    public static Object getValue(String key){
        String[] keys = key.split("[.]");
        Map ymlInfo = (Map) ymls.get(nowFileName.get()).clone();
        for (int i = 0; i < keys.length; i++) {
            Object value = ymlInfo.get(keys[i]);
            if (i < keys.length - 1){
                ymlInfo = (Map) value;
            }else if (value == null){
                return "";
            }else {
                String g;
                String keyChild;
                String v1 = (String)value;
                for(Matcher m = p1.matcher(v1); m.find(); value = v1.replace(g, (String)getValue(keyChild))) {
                    g = m.group();
                    keyChild = g.replaceAll("\\$\\{", "").replaceAll("\\}", "");
                }
                return value;
            }
        }
        return "";
    }

    /**
     * 读取yml文件中的某个value
     * @param fileName  yml名称
     * @param key
     * @return Object
     */
    public static Object getValue(String fileName , String key){
        try {
            loadYml(fileName);
            return getValue(key);
        }catch (Exception e){
            return "";
        }
    }

    /**
     * 框架私有方法，非通用。
     * 获取 server.servlet.context-path的值
     * @return
     */
    public static String getContextPath(){
        return getValueToString("adminPath");
    }

    /**
     * 读取自定义yml文件中的某个value，返回String
     * @param fileName
     * @param key
     * @return String
     */
    public static String getValueToString(String fileName , String key){
        return (String)getValue(fileName , key);
    }

    /**
     * 从框架中默认的yml文件中读取
     * @param key
     * @return
     */
    public static String getValueToString(String key){
        String msg = "";
        for (int i = 0; i < DEFAULT_CONFIG_FILE.length; i++) {
            msg = (String)getValue(DEFAULT_CONFIG_FILE[i] , key);
            if (EmptyUtil.isNoEmpty(msg)){
                return msg;
            }
        }
        throw new RuntimeException("key不存在,或无返回值！");
    }

    /**
     * Test
     * @param args
     */
    public static void main(String[] args) {
        System.out.println(getValueToString("productName"));
//        System.out.println(getValueToString("application.yml", "shiro.defaultFilterChainDefinitions"));
    }
}
